import React from 'react';
import { Modal, Row, Col, Button, Table, Select , DatePicker, Pagination, message, Icon } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import Moment from 'moment';

const { Option } = Select;

export default class InquireWarehouseVoucher extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          visible: false,
          tableData: [],
          startDate: undefined, // 开始日期
          endDate: undefined, // 截止日期
          status: undefined, // 单据状态
          rowId: '', // 选中行id
          total: 0, // 总条数
          page: 1, // 页数
          pageSize: 10, // 每页的条数
          inOperLocID: '', // 保存入库id
          showDetailList: false,
          detailWidth: '',
          columns: [],
          language: JSON.parse(window.sessionStorage.userData),
          ChineseEnglishSize:{}
        };
        this.columns = [
            {
                key: 1,
                title: this.state.language.language == 'EN'?'Supplier':'供应商',
                dataIndex: 'vendorDesc',
                align: "center",
                width: '28%'
            },
            {
                key: 2,
                title: this.state.language.language == 'EN'?'Incoming department':'入库科室',
                dataIndex: 'inOperLocDesc',
                align: "center",
                width: '16%',
            },
            {
                key: 3,
                title: this.state.language.language == 'EN'?'Inbound order number':'入库单号',
                dataIndex: 'No',
                align: "center",
                width: '20%',
            },
            {
                key: 4,
                title: this.state.language.language == 'EN'?'Document status':'单据状态',
                dataIndex: 'stateDesc',
                align: "center",
                width: '16%',
            },
            {
                key: 5,
                title: this.state.language.language == 'EN'?'Date of inbound':'入库日期',
                dataIndex: 'createDate',
                align: "center",
            }
        ]
      }
        
    componentDidMount() {
        // 获取列表数据
        this.props.onRef(this);
        this.getCheckPopup();
    }

    // 获取明系列表头数据
    getCheckPopup = () => {
        let data = {
            params: [{
                compontName: 'MaterialInquireWarehouseList',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => { this.columnRef.onOpenModel();}}>{language.language== 'EN' ? item.enDescripts : item.title}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({columns: filterArr, detailWidth: res.totalWidth})
                }
            }
        })
    };
    // 设置默认日期
    setTacitlyApproveDate() {
        let data = this.props.handleThis.state.tacitlyApproveData;
        if (data) {
            this.setState({startDate: Moment(data.startDate), endDate: Moment(data.endDate)});
        } else {
            this.setState({startDate: Moment(), endDate: Moment()});
        }
    }
    
    // 打开弹框
    showModal = (v) => {
        this.setState({
          visible: true,
          ChineseEnglishSize:v
        }, () => {
            this.handleQuery();
            // 当this.state.startDate有值则不需要重新加载
            if (this.state.startDate === undefined) {
                this.setTacitlyApproveDate();
            }
        });
    }
    
    // 确定
    handleOk = (e) => {
        let {ChineseEnglishSize} = this.state;
        if (this.state.rowId) {
            this.props.handleThis.getEchoData(this.state.rowId);
            this.handleCancel()
            // 重置明细录入
            this.props.handleThis.resetFieldsFrom()
        } else {
            message.error(ChineseEnglishSize.MaterialStorageOrderMakingselectOperatedDataTips ? ChineseEnglishSize.MaterialStorageOrderMakingselectOperatedDataTips.descripts:'请选择一条需要操作的数据');
        }
    }
    
    // 关闭
    handleCancel = (e) => {
        this.setState({
          visible: false,
        });
    }

    // 获取列表数据
    getTableData(startDate, endDate, status) {
        this.setState({loading: true})
        let {page, pageSize} = this.state;
        let data = {
            params: [
                {
                    inOperLocID: this.props.inOperLocID, // 库存项Id
                    startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : '',
                    endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : '',
                    statusID: status
                }
            ],
            pagination: [
                {
                    pageSize: pageSize,
                    currentPage: page,
                    sort: "",
                    dir: "",
                }
            ],
        }
        $http.post('urlS', this, {
            code: "02060010",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for(var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i;
                    }
                    this.setState({tableData: res.rows, total: res.total, loading: false})
                }
            }
        })
    }

    // 查询列表数据
    handleQuery = () => {
        this.setState({page: 1, pageSize: 10, inOperLocID: this.props.inOperLocID}, () => {
            let {startDate, endDate, status} = this.state;
            this.getTableData(startDate, endDate, status);
        })
    }

    // 查询条件---开始日期
    handleStartDate = (e) => {
        this.setState({startDate: e})
    }

    // 查询条件---截止日期
    handleEndDate = (e) => {
        this.setState({endDate: e})
    }

    // 查询条件---单据状态
    handleStatus = (e) => {
        this.setState({status: e})
    }

    // 取消选中
    handleUncheck() {
        this.setState({rowId: ''});
    }

    // 设置行属性
	onClickRow = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.rowId === '') {
					// 保存行数据以及ID
					this.setState({rowId: record.inOperID})
				} else {
					if (this.state.rowId !== record.inOperID) {
						this.setState({rowId: record.inOperID})
					}
				}
            },
            onDoubleClick: () => {
                // 保存行数据以及ID
                this.setState({rowId: record.inOperID}, () => {
                    this.handleOk();
                })
            }
		}
  	}
  
	// 表格行的类名
	setRowClassName = (record) => {
		return record.inOperID === this.state.rowId ? 'clickRowStyle' : '';
    }
    
    // 页码改变的回调，参数是改变后的页码及每页条
    onChange = (page, pageSize) => {
        this.setState({page: page, pageSize: this.state.pageSize}, () => {
            let {startDate, endDate, status} = this.state;
            this.getTableData(startDate, endDate, status)
        })
    }

    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({page: 1, pageSize: size}, () => {
            let {startDate, endDate, status} = this.state;
            this.getTableData(startDate, endDate, status);
        })
    }

    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    //组件权限编辑器
    onColumnRef = (ref) => {
        this.columnRef = ref;
    };
    render() {
        let { columns, detailWidth,ChineseEnglishSize } = this.state;
        return (
            <Modal
				title={ChineseEnglishSize.MaterialStorageOrderMakinginquiryReceiptForm ? ChineseEnglishSize.MaterialStorageOrderMakinginquiryReceiptForm.descripts:'查询入库单'}
				visible={this.state.visible}
				onOk={this.handleOk}
                onCancel={this.handleCancel}
                okText={ChineseEnglishSize.MaterialStorageOrderMakingdetermine ? ChineseEnglishSize.MaterialStorageOrderMakingdetermine.descripts:'确定'}
                cancelText={ChineseEnglishSize.MaterialStorageOrderMakingcancel ? ChineseEnglishSize.MaterialStorageOrderMakingcancel.descripts:'取消'}
                width={800}
			>
                <div style={{height: '445px'}}>
                    <Row style={{marginBottom: '24px'}}>
                    {ChineseEnglishSize.MaterialStorageOrderMakingstartDate ? ChineseEnglishSize.MaterialStorageOrderMakingstartDate.descripts:'起始日期：'}<DatePicker allowClear={false} style={{width: '130px', marginRight: '20px'}} format="YYYY-MM-DD" value={this.state.startDate} onChange={this.handleStartDate} />
                    {ChineseEnglishSize.MaterialStorageOrderMakingendDate ? ChineseEnglishSize.MaterialStorageOrderMakingendDate.descripts:'截止日期：'}<DatePicker allowClear={false} style={{width: '130px', marginRight: '20px'}} format="YYYY-MM-DD" value={this.state.endDate} onChange={this.handleEndDate} />
                    {ChineseEnglishSize.MaterialStorageOrderMakingstatus ? ChineseEnglishSize.MaterialStorageOrderMakingstatus.descripts:'单据状态：'}<Select allowClear placeholder={ChineseEnglishSize.MaterialStorageOrderMakingstatus ? ChineseEnglishSize.MaterialStorageOrderMakingstatus.descripts:'单据状态'} style={{width: '130px', marginRight: '20px'}} value={this.state.status} onChange={this.handleStatus} >
                                        {this.props.SelectData.inOpStatus && this.props.SelectData.inOpStatus.map(item => {
                                            return <Option key={item.id} value={item.id} title={item.descripts + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                </Select>
                        <Button onClick={this.handleQuery} style={{background: 'rgba(255,255,255,1)'}}>{ChineseEnglishSize.MaterialStorageOrderMakingsearch ? ChineseEnglishSize.MaterialStorageOrderMakingsearch.descripts:'查询'}</Button>
                    </Row>
                    <Table
                        columns={columns.length >0 ? columns : this.columns}
                        dataSource={this.state.tableData}
                        pagination={false}
                        style={{overflow: 'auto', height: '350px'}}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                    />

                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                                      loading={this.state.loading} onChange={this.onChange.bind(this)} />
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='MaterialInquireWarehouseList'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getCheckPopup}
                    />
                </div>
			</Modal>
        )
    }
}